<?php 
class Instance
{
	const INSTANCE_STATUS_ACTIVE 	= 'Active';
	const INSTANCE_STATUS_SUSPENDED = 'Suspended';
	
	public $m_CommSvcObj;
	
	public function __construct()
	{
		$this->m_CommSvcObj = new CommunicateService();
	}
	
	public function Create($hostname,$domain,$start_time,$end_time,$foreign_key=null,$deploy_appcloud=true)
	{
		//Get Fully qualified domain name 
		$fqdn = strtolower(str_replace(" ", "", $hostname.'.'.$domain));
		
		//Create Web root folder
		$siteroot = WEB_ROOT_PATH.DIRECTORY_SEPARATOR.$fqdn;
		$webroot = $siteroot.DIRECTORY_SEPARATOR.WWW_FOLDER;
		$logroot = $siteroot.DIRECTORY_SEPARATOR.LOG_FOLDER;
		$backuproot = BACKUP_ROOT_PATH.DIRECTORY_SEPARATOR.$fqdn;		
		@mkdir($siteroot,FILE_PERM_ON_WORK,true);
		@mkdir($webroot,FILE_PERM_ON_WORK,true);
		@mkdir($logroot,FILE_PERM_ON_WORK,true);
		@mkdir($backuproot,FILE_PERM_ON_WORK,true);
		

		
		//Generate apache config file
		$templateFile = AGENT_ROOT_PATH.DIRECTORY_SEPARATOR.'template'.DIRECTORY_SEPARATOR.'hosting.tpl.conf';
		$templateData = file_get_contents($templateFile);
		$templateData = str_replace('{$WEBROOT}',WEB_ROOT_PATH,$templateData);
		$templateData = str_replace('{$HOSTNAME}',$fqdn,$templateData);
		$targetFile = APACHE_CONFIG_PATH.DIRECTORY_SEPARATOR.$fqdn;
		file_put_contents($targetFile, $templateData);
		
		//Enable the new host
		$cmd = APACHE_EN_SITE_CMD." ".$fqdn;
		exec($cmd,$output);
		
		//Reload apache
		$cmd = APACHE_CONTROL_CMD." graceful";
		exec($cmd,$output);
		
		//Create DNS Record
		$dnsSvc = new DNS($domain);
		$dnsSvc->createARecord($hostname,SERVER_IP);
		
		//Create database
		$conn = mysql_connect(MYSQL_HOST,MYSQL_USER,MYSQL_PASSWORD);
		$dbname 	= "udb_".$hostname;
		$dbuser 	= "udb_".$hostname;
		$dbpasswd 	= substr(md5(rand()),0,12);
		$sql = "CREATE DATABASE  IF NOT EXISTS `$dbname`; ";
		mysql_query($sql,$conn);
		
		//Create DB users
		$sql = "CREATE USER '$dbuser'@'localhost' IDENTIFIED BY  '$dbpasswd';";
		mysql_query($sql,$conn);	

		//if the user exists then try to reset the password
		$sql = "SET PASSWORD FOR  '$dbuser'@'localhost' = PASSWORD('$dbpasswd')";
		mysql_query($sql,$conn);
		
		//Grant permission to new DB
		$sql = "GRANT ALL PRIVILEGES ON  `$dbname` . * TO  '$dbuser'@'localhost';";
		mysql_query($sql,$conn);
		
		//Callback to Control Center to create a new host instance
		$instanceConfig = array(
			"foreign_key" 	=>	$foreign_key,
			"hostname"		=>	$hostname,
			"domain" 		=>	$domain,
			"dbname"		=>	$dbname,
			"dbuser"		=>	$dbuser,
			"dbpasswd"		=>	$dbpasswd,
			"start_time"	=> 	$start_time,
			"end_time"		=> 	$end_time,
			"status"		=>  self::INSTANCE_STATUS_ACTIVE
		);
		$this->m_CommSvcObj->notifyInstanceCreated($instanceConfig);
		
		
		if($deploy_appcloud)
		{
			$cloud = new Appcloud();
			$cloud->Deploy($instanceConfig);
			//triger instance usage stat
			$this->StatUsage($hostname, $domain,$foreign_key);
		}
		
		//sets file permission
		$cmd = CHOWN_CMD." -R ".FILE_OWNER.":".FILE_GROUP." $siteroot";
		exec($cmd,$output);
		
		$cmd = CHMOD_CMD." -R 755 $siteroot";
		exec($cmd,$output);
		
		return "Instance $fqdn Created";
	}
	
	
	public function Destory($hostname,$domain,$foreign_key=null)
	{		
		//Create a backup before destory
		$this->Backup($hostname,$domain,'latest');
		
		//Get Fully qualified domain name 
		$fqdn = strtolower(str_replace(" ", "", $hostname.'.'.$domain));
		$siteroot = WEB_ROOT_PATH.DIRECTORY_SEPARATOR.$fqdn;
		
		//Disable the host
		$cmd = APACHE_DIS_SITE_CMD." ".$fqdn;
		exec($cmd,$output);
		
		//Remove host config file
		$targetFile = APACHE_CONFIG_PATH.DIRECTORY_SEPARATOR.$fqdn;
		unlink($targetFile);
		
		//Reload apache
		$cmd = APACHE_CONTROL_CMD." graceful";
		exec($cmd,$output);
		
		//Delete DNS Record
		$dnsSvc = new DNS($domain);
		$dnsSvc->deleteARecord($hostname,SERVER_IP);
		
		//Drop database
		$conn = mysql_connect(MYSQL_HOST,MYSQL_USER,MYSQL_PASSWORD);
		$dbname 	= "udb_".$hostname;
		$dbuser 	= "udb_".$hostname;
		$dbpasswd 	= substr(md5(rand()),0,12);
		$sql = "DROP DATABASE IF EXISTS `$dbname`; ";
		mysql_query($sql,$conn);
		
		//Drop database user
		$sql = "DROP USER '$dbuser'@'localhost' ; ";
		mysql_query($sql,$conn);			
		
		//Remove all users files
		$cmd = RM_CMD." -rf ' $siteroot'";
		exec($cmd,$output);		
		
		//notify Instance Destroyed
		$instanceConfig = array(
			"foreign_key" 	=>	$foreign_key,
			"hostname"		=>	$hostname,
			"domain" 		=>	$domain			
		);
		$this->m_CommSvcObj->notifyInstanceDestroyed($instanceConfig);
		return "Instance $fqdn Destroyed";
	}	
	
	public function Suspend($hostname,$domain,$foreign_key=null)
	{
		//Get Fully qualified domain name 
		$fqdn = strtolower(str_replace(" ", "", $hostname.'.'.$domain));
		$siteroot = WEB_ROOT_PATH.DIRECTORY_SEPARATOR.$fqdn;
		
		//Disable the host
		$cmd = APACHE_DIS_SITE_CMD." ".$fqdn;
		exec($cmd,$output);
		
		//Reload apache
		$cmd = APACHE_CONTROL_CMD." graceful";
		exec($cmd,$output);
		
		//Set 0 permission mask to site root
		$cmd = CHMOD_CMD." ".FILE_PERM_ON_SUSPEND." $siteroot";
		exec($cmd,$output);
		
		//notify Instance Status Updated
		$instanceConfig = array(
			"foreign_key" 	=>	$foreign_key,
			"hostname"		=>	$hostname,
			"domain" 		=>	$domain,
			"status"		=>	self::INSTANCE_STATUS_SUSPENDED
		);
		$this->m_CommSvcObj->notifyInstanceStatusChanged($instanceConfig);
		return "Instance $fqdn Suspended";
	}		
	
	public function Resume($hostname,$domain,$foreign_key=null)
	{		
		//Get Fully qualified domain name 
		$fqdn = strtolower(str_replace(" ", "", $hostname.'.'.$domain));
		$siteroot = WEB_ROOT_PATH.DIRECTORY_SEPARATOR.$fqdn;
		
		//Disable the host
		$cmd = APACHE_EN_SITE_CMD." ".$fqdn;
		exec($cmd,$output);
		
		//Reload apache
		$cmd = APACHE_CONTROL_CMD." graceful";
		exec($cmd,$output);
		
		//Set working permission mask to site root
		$cmd = CHMOD_CMD." ".FILE_PERM_ON_WORK." $siteroot";
		exec($cmd,$output);		
		
		//notify Instance Status Updated
		$instanceConfig = array(
			"foreign_key" 	=>	$foreign_key,
			"hostname"		=>	$hostname,
			"domain" 		=>	$domain,
			"status"		=>	self::INSTANCE_STATUS_ACTIVE
		);
		$this->m_CommSvcObj->notifyInstanceStatusChanged($instanceConfig);
		return "Instance $fqdn Resumed";
	}
	
	public function Backup($hostname,$domain,$archive_name=null)
	{
		//Get Fully qualified domain name 
		$fqdn = strtolower(str_replace(" ", "", $hostname.'.'.$domain));
		$siteroot = WEB_ROOT_PATH.DIRECTORY_SEPARATOR.$fqdn;
		if(!$archive_name){
			$archive_name = date('YmdHis');
		}
		$fileName = $fqdn.'-'.$archive_name.'.tar.gz';
		
		//check if backup folder exists
		$backupFolder = BACKUP_ROOT_PATH.DIRECTORY_SEPARATOR.$fqdn;
		if(!is_dir($backupFolder))
		{
			@mkdir($backupFolder,FILE_PERM_ON_WORK,true);
		}		
		
		//Dump users database to file database.sql
		$dbname 	= "udb_".$hostname;
		$dumpFile   = $siteroot.DIRECTORY_SEPARATOR.'database.sql';
		$cmd = MYSQLDUMP_CMD." -u".MYSQL_USER." -p".MYSQL_PASSWORD." $dbname > $dumpFile";
		exec($cmd,$output);	

		//Create tarball for all users files and database.sql
		$cmd = TAR_CMD." -czf ".$backupFolder.$fileName." -C $siteroot ./";
		exec($cmd,$output);	
				
		return true;		
	}
	
	public function SetAlias($alias,$hostname,$domain,$foreign_key=null)
	{
		//Get Fully qualified domain name 
		$fqdn = strtolower(str_replace(" ", "", $hostname.'.'.$domain));
		$siteroot = WEB_ROOT_PATH.DIRECTORY_SEPARATOR.$fqdn;
		
		//Generate apache config file
		$configFile = APACHE_CONFIG_PATH.DIRECTORY_SEPARATOR.$fqdn;
		$templateData = file_get_contents($configFile);
		if(preg_match("/ServerAlias/si",$templateData))
		{
			//found ServerAlias replace it 
			$pattern = "/(ServerAlias.*?)\n/si";
			$replacement = "ServerAlias $alias \n";
			preg_match($pattern,$templateData,$matches);
			$templateData = preg_replace($pattern, $replacement, $templateData);
		}
		else
		{
			//append ServerAlias after ServerName 	
			$pattern = "/(ServerName.*?)\n/si";
			$replacement = "$1\n\tServerAlias $alias \n";
			preg_match($pattern,$templateData,$matches);
			$templateData = preg_replace($pattern, $replacement, $templateData);
		}		
		file_put_contents($configFile, $templateData);
		
		//notify Instance Status Updated
		$instanceConfig = array(
			"foreign_key" 	=>	$foreign_key,
			"hostname"		=>	$hostname,
			"domain" 		=>	$domain,
			"alias"			=>	$alias
		);
		$this->m_CommSvcObj->notifyInstanceStatusChanged($instanceConfig);
		
		return true;
	}
	
	public function StatUsage($hostname,$domain,$foreign_key=null)
	{
		//Get Fully qualified domain name 
		$fqdn = strtolower(str_replace(" ", "", $hostname.'.'.$domain));
		$siteroot = WEB_ROOT_PATH.DIRECTORY_SEPARATOR.$fqdn;
		$webroot = $siteroot.DIRECTORY_SEPARATOR.WWW_FOLDER;
		$logroot = $siteroot.DIRECTORY_SEPARATOR.LOG_FOLDER;
		$dbroot  = MYSQL_DATDIR.DIRECTORY_SEPARATOR.MYSQL_DBNAME_PREFIX.$hostname;
		$backuproot = BACKUP_ROOT_PATH.DIRECTORY_SEPARATOR.$fqdn;
		
		//get storage usage data
		$cmd = DU_CMD." -sb '$webroot'";
		$output=null;
		exec($cmd,$output);	
		preg_match("/([0-9]+)\s\S.*$/si",$output[0],$match);
		$storage_usage = (int)$match[1];
		
		//get database usage data
		$cmd = DU_CMD." -sb '$dbroot'";
		$output=null;
		exec($cmd,$output);	
		preg_match("/([0-9]+)\s\S.*$/si",$output[0],$match);
		$database_usage = (int)$match[1];
		
		//get backup usage data
		$cmd = DU_CMD." -sb '$backuproot'";
		$output=null;
		exec($cmd,$output);	
		preg_match("/([0-9]+)\s\S.*$/si",$output[0],$match);
		$backup_usage = (int)$match[1];
				
		//get log usage data
		$cmd = DU_CMD." -sb '$logroot'";
		$output=null;
		exec($cmd,$output);	
		preg_match("/([0-9]+)\s\S.*$/si",$output[0],$match);
		$log_usage = (int)$match[1];
		
		//notify Instance Status Updated
		$instanceConfig = array(
			"foreign_key" 	=>	$foreign_key,
			"hostname"		=>	$hostname,
			"domain" 		=>	$domain,
			"storage_usage"	=>	$storage_usage,
			"database_usage"=>	$database_usage,
			"backup_usage"	=>	$backup_usage,
			"log_usage"		=>	$log_usage
		);
		$this->m_CommSvcObj->notifyInstanceUsageUpdated($instanceConfig);
		return "Usage Stat Updated $fqdn ";
	}
	
	public function UpdateRepos($hostname,$domain,$foreign_key=null)
	{
		//Get Fully qualified domain name 
		$fqdn = strtolower(str_replace(" ", "", $hostname.'.'.$domain));
		$siteroot = WEB_ROOT_PATH.DIRECTORY_SEPARATOR.$fqdn;
		$webroot = $siteroot.DIRECTORY_SEPARATOR.WWW_FOLDER;
		
		//Disable the host
		$cmd = SVN_CMD." update ".$webroot;
		exec($cmd,$output);
		
		//sets file permission
		$cmd = CHOWN_CMD." -R ".FILE_OWNER.":".FILE_GROUP." $webroot";
		exec($cmd,$output);
		
		$cmd = CHMOD_CMD." -R 755 $webroot";
		exec($cmd,$output);
		
		$result = implode("\n", $output);	
		$result = "Instance $fqdn \n\n".$result;	
		return $result;
	}	
}
?>